<?php
// 启用错误显示
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 加载数据库配置
require_once __DIR__ . '/config/database.php';

// 检查是否为管理员
session_start();
$is_admin = isset($_SESSION['username']) && $_SESSION['username'] === 'admin';

// 如果不是管理员且不是本地访问，则拒绝访问
if (!$is_admin && $_SERVER['REMOTE_ADDR'] !== '127.0.0.1' && $_SERVER['REMOTE_ADDR'] !== '::1') {
    header('HTTP/1.1 403 Forbidden');
    echo "访问被拒绝。此页面仅供管理员使用。";
    exit;
}

// 设置页面头部
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>初始化充值表</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
        }
        h1, h2 {
            margin-bottom: 20px;
        }
        .card {
            background: #f9f9f9;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .success {
            color: green;
            font-weight: bold;
        }
        .error {
            color: red;
            font-weight: bold;
        }
        .warning {
            color: orange;
            font-weight: bold;
        }
        pre {
            background: #f5f5f5;
            padding: 15px;
            border-radius: 4px;
            overflow: auto;
        }
        button {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 10px;
        }
        button:hover {
            background: #45a049;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
    </style>
</head>
<body>
    <h1>充值表初始化工具</h1>
    
    <div class="card">
        <h2>数据库连接</h2>
        <?php
        try {
            // 测试数据库连接
            $stmt = $pdo->query("SELECT 1 AS test");
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            echo "<p class='success'>✓ 数据库连接成功</p>";
        } catch (PDOException $e) {
            echo "<p class='error'>✗ 数据库连接失败: " . htmlspecialchars($e->getMessage()) . "</p>";
            echo "<p>请检查 config/database.php 文件中的数据库配置</p>";
            exit;
        }
        ?>
    </div>
    
    <div class="card">
        <h2>表结构检查</h2>
        <?php
        // 检查表是否存在
        $tables = [];
        $stmt = $pdo->query("SHOW TABLES");
        while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
            $tables[] = $row[0];
        }
        
        $deposit_table_exists = in_array('deposit_records', $tables);
        
        if ($deposit_table_exists) {
            echo "<p class='success'>✓ deposit_records 表已存在</p>";
            
            // 检查表结构
            $stmt = $pdo->query("DESCRIBE deposit_records");
            $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $column_names = array_column($columns, 'Field');
            $required_columns = [
                'id', 'user_id', 'amount', 'payment_method', 
                'random_code', 'status', 'admin_note', 
                'created_at', 'processed_at'
            ];
            
            $missing_columns = array_diff($required_columns, $column_names);
            
            if (empty($missing_columns)) {
                echo "<p class='success'>✓ 表结构完整</p>";
                
                echo "<h3>当前表结构</h3>";
                echo "<table>";
                echo "<tr><th>字段</th><th>类型</th><th>Null</th><th>Key</th><th>Default</th><th>Extra</th></tr>";
                
                foreach ($columns as $column) {
                    echo "<tr>";
                    echo "<td>" . htmlspecialchars($column['Field']) . "</td>";
                    echo "<td>" . htmlspecialchars($column['Type']) . "</td>";
                    echo "<td>" . htmlspecialchars($column['Null']) . "</td>";
                    echo "<td>" . htmlspecialchars($column['Key']) . "</td>";
                    echo "<td>" . htmlspecialchars($column['Default'] ?? 'NULL') . "</td>";
                    echo "<td>" . htmlspecialchars($column['Extra']) . "</td>";
                    echo "</tr>";
                }
                
                echo "</table>";
                
                // 检查索引
                $stmt = $pdo->query("SHOW INDEX FROM deposit_records");
                $indexes = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo "<h3>当前索引</h3>";
                echo "<table>";
                echo "<tr><th>键名</th><th>列名</th><th>唯一</th><th>类型</th></tr>";
                
                foreach ($indexes as $index) {
                    echo "<tr>";
                    echo "<td>" . htmlspecialchars($index['Key_name']) . "</td>";
                    echo "<td>" . htmlspecialchars($index['Column_name']) . "</td>";
                    echo "<td>" . ($index['Non_unique'] ? '否' : '是') . "</td>";
                    echo "<td>" . htmlspecialchars($index['Index_type']) . "</td>";
                    echo "</tr>";
                }
                
                echo "</table>";
                
            } else {
                echo "<p class='warning'>⚠ 表结构不完整，缺少以下字段：</p>";
                echo "<ul>";
                foreach ($missing_columns as $column) {
                    echo "<li>" . htmlspecialchars($column) . "</li>";
                }
                echo "</ul>";
            }
            
        } else {
            echo "<p class='error'>✗ deposit_records 表不存在</p>";
        }
        ?>
        
        <form method="post">
            <input type="hidden" name="action" value="create_table">
            <button type="submit">创建/修复充值表</button>
        </form>
    </div>
    
    <?php
    // 处理表创建请求
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_table') {
        echo '<div class="card">';
        echo '<h2>表创建/修复结果</h2>';
        
        try {
            // 创建充值记录表
            $create_table_sql = "
                CREATE TABLE IF NOT EXISTS deposit_records (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id INT NOT NULL,
                    amount DECIMAL(10,2) NOT NULL,
                    payment_method VARCHAR(50) NOT NULL,
                    random_code VARCHAR(10) NOT NULL,
                    status ENUM('pending', 'processing', 'completed', 'failed', 'cancelled') DEFAULT 'pending',
                    admin_note TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    processed_at TIMESTAMP NULL,
                    INDEX idx_user_id (user_id),
                    INDEX idx_random_code (random_code),
                    INDEX idx_status (status)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            ";
            
            $pdo->exec($create_table_sql);
            
            // 检查表是否创建成功
            $stmt = $pdo->query("SHOW TABLES LIKE 'deposit_records'");
            if ($stmt->rowCount() > 0) {
                echo "<p class='success'>✓ 充值表创建/修复成功</p>";
                
                // 检查列是否存在，如果不存在则添加
                $stmt = $pdo->query("DESCRIBE deposit_records");
                $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $column_names = array_column($columns, 'Field');
                
                $required_columns = [
                    'random_code' => "ALTER TABLE deposit_records ADD COLUMN random_code VARCHAR(10) NOT NULL AFTER payment_method",
                    'admin_note' => "ALTER TABLE deposit_records ADD COLUMN admin_note TEXT AFTER status",
                    'processed_at' => "ALTER TABLE deposit_records ADD COLUMN processed_at TIMESTAMP NULL AFTER created_at"
                ];
                
                foreach ($required_columns as $column => $sql) {
                    if (!in_array($column, $column_names)) {
                        try {
                            $pdo->exec($sql);
                            echo "<p class='success'>✓ 添加了 {$column} 列</p>";
                        } catch (PDOException $e) {
                            echo "<p class='error'>✗ 添加 {$column} 列失败: " . htmlspecialchars($e->getMessage()) . "</p>";
                        }
                    }
                }
                
                // 检查索引是否存在，如果不存在则添加
                $stmt = $pdo->query("SHOW INDEX FROM deposit_records");
                $indexes = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $index_names = array_unique(array_column($indexes, 'Key_name'));
                
                $required_indexes = [
                    'idx_random_code' => "ALTER TABLE deposit_records ADD INDEX idx_random_code (random_code)",
                    'idx_status' => "ALTER TABLE deposit_records ADD INDEX idx_status (status)"
                ];
                
                foreach ($required_indexes as $index => $sql) {
                    if (!in_array($index, $index_names)) {
                        try {
                            $pdo->exec($sql);
                            echo "<p class='success'>✓ 添加了 {$index} 索引</p>";
                        } catch (PDOException $e) {
                            echo "<p class='error'>✗ 添加 {$index} 索引失败: " . htmlspecialchars($e->getMessage()) . "</p>";
                        }
                    }
                }
                
                echo "<p>请刷新页面查看最新的表结构</p>";
                echo "<script>setTimeout(function() { window.location.reload(); }, 3000);</script>";
            } else {
                echo "<p class='error'>✗ 充值表创建失败</p>";
            }
        } catch (PDOException $e) {
            echo "<p class='error'>✗ 执行SQL失败: " . htmlspecialchars($e->getMessage()) . "</p>";
        }
        
        echo '</div>';
    }
    ?>
    
    <div class="card">
        <h2>数据库信息</h2>
        <?php
        try {
            // 获取MySQL版本
            $stmt = $pdo->query("SELECT VERSION() as version");
            $version = $stmt->fetch(PDO::FETCH_ASSOC);
            echo "<p>MySQL版本: " . htmlspecialchars($version['version']) . "</p>";
            
            // 获取数据库名称
            $stmt = $pdo->query("SELECT DATABASE() as db_name");
            $db = $stmt->fetch(PDO::FETCH_ASSOC);
            echo "<p>当前数据库: " . htmlspecialchars($db['db_name']) . "</p>";
            
            // 获取表信息
            echo "<h3>数据库表</h3>";
            echo "<ul>";
            foreach ($tables as $table) {
                echo "<li>" . htmlspecialchars($table) . "</li>";
            }
            echo "</ul>";
        } catch (PDOException $e) {
            echo "<p class='error'>✗ 获取数据库信息失败: " . htmlspecialchars($e->getMessage()) . "</p>";
        }
        ?>
    </div>
    
    <div class="card">
        <h2>返回链接</h2>
        <p><a href="index.php">返回主页</a></p>
        <p><a href="ajax_debug.php">AJAX调试工具</a></p>
        <p><a href="debug_deposit.php">充值调试工具</a></p>
    </div>
</body>
</html>
